package com.dhgate.spu.analysis.collector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhgate.spu.analysis.bean.ProdLine;
import com.dhgate.spu.analysis.bean.Product;
import com.dhgate.spu.analysis.bean.SpuStandard;
import com.dhgate.spu.analysis.consts.SpuStandardConsts;
import com.dhgate.spu.analysis.util.CommonUtil;
import com.dhgate.spu.analysis.util.StringUtil;

/** 
 * @Description: TODO
 *
 * @author zhaowei
 * @version 1.0
 * @create time 2014-4-8 下午5:17:52
 */
public class ExtractCollector extends StandardCollector {

	private static final Logger logger = LoggerFactory.getLogger(ExtractCollector.class);

	public void init() throws Exception {

	}

	@Override
	public void process(Product p) {
		super.process(p);
	}

	private Map<String, Map<String, String>> outMap = new HashMap<String, Map<String, String>>();

	public Map<String, Map<String, String>> getOutMap() {
		return outMap;
	}

	public void setOutMap(Map<String, Map<String, String>> outMap) {
		this.outMap = outMap;
	}

	//{spubrand1-spumodel2-843500.txt={1188281={spumodel=[m8, m9, mx, mx2, mx3], spubrand=[meizu]}} }
	//list:[qualcomm602a, qualcomm800]
	//
	@SuppressWarnings("unchecked")
	public void regulateProduct(Product p) {
		logger.debug("enter into ExtractCollector regulateProduct");
		ProdLine prodLine = SpuStandardConsts.getProdLine(p.getProdLineId());
		Map<String, Object> data_map = prodLine.getData_map();
		Iterator<String> iterator = data_map.keySet().iterator();
		while (iterator.hasNext()) {
			String filenameKey = iterator.next();
			//去掉
			String filename = filenameKey.substring(0, filenameKey.length() - 5);
			String[] filenamePartArr = filename.split("-");

			Object obj = data_map.get(filenameKey);
			//object: List<String>  或 Map<id,map<字段,List<String>>    Map<id,String>

			if (filenameKey.endsWith("1")) { //1188281:Meizu:魅族|M8,M9,MX,MX2,MX3    Map<id,map<字段,List<String>>
				Map<String, Map<String, List<String>>> map = (Map<String, Map<String, List<String>>>) obj;
				String extattrValId = null;
				for (int i = 0; i < filenamePartArr.length; i++) {
					String part = filenamePartArr[i];
					boolean yFillByDb = false;
					String extFieldName = part;
					if (part.contains("#")) {
						String[] fieldAttrIdArr = part.split("#");
						extFieldName = fieldAttrIdArr[0];
						String attrId = fieldAttrIdArr[1];
						extattrValId = fillByDb(extFieldName, attrId, p);
						if (StringUtils.isEmpty(extattrValId) || yAbandonAttrValId(p,extattrValId)) {
							List<String> enNameList = prodLine.getFilename2enNamelistMap().get(filenameKey);
							Map<String, String> enname2attrValIdMap = prodLine.getFilename2ennametoattrvalidMap().get(filenameKey);
							extattrValId = extractAssociatedField(p, enNameList, enname2attrValIdMap, map, filenamePartArr[i + 1],
									Long.parseLong(attrId), extFieldName);
							if (StringUtils.isBlank(extattrValId))
								break;
						}
					} else {
						if (StringUtils.isNotBlank(extattrValId) && !yAbandonAttrValId(p,extattrValId)) {
							logger.debug("extattrValId="+extattrValId+" map.get(extattrValId)="+map.get(extattrValId));
							if(map.get(extattrValId)!=null){
								List<String> attrValList = map.get(extattrValId).get(extFieldName);
								extractField(attrValList, p, extFieldName, true);
							}
							
						}
					}
				}
			} else if (filenameKey.endsWith("2")) { //a,b
				List<String> list = (List<String>) obj;
				extractField(list, p, filenamePartArr[0], true);

			} else if (filenameKey.endsWith("3")) {//1188281:Meizu:魅族
				String fieldName = filenamePartArr[0].split("#")[0];
				String attrId = filenamePartArr[0].split("#")[1];

				String extattrValId = fillByDb(fieldName, attrId, p);
				if (StringUtils.isEmpty(extattrValId) || yAbandonAttrValId(p,extattrValId)) {
					List<String> enNameList = prodLine.getFilename2enNamelistMap().get(filenameKey);
					String enName = extractField(enNameList, p, fieldName, false);
					Map<String, String> enName2attrValIdMap = (Map<String, String>) obj;
					String attrValId = enName2attrValIdMap.get(enName);
					if (StringUtils.isBlank(attrValId)) {
						break;
					}
					//比数据库字段多了个spu
					p.setField(fieldName, attrValId);
					List<Long> attrValIdList = new ArrayList<Long>();
					attrValIdList.add(Long.parseLong(attrValId));
					p.setAttrValIdList(Long.parseLong(attrId), attrValIdList);
					//添加新的属性id
					p.addAttrValIdSet(Long.parseLong(attrValId));
					//清理此属性关联的无效的属性id
					removeAttrValId(p, Long.parseLong(attrId));
					buildOutMap(p.getItemCode(),Long.parseLong(attrId),fieldName,attrValId,enName);
				}
			}
		}

	}

	/**
	 * 
	 * @Description: 数据库有属性值就不用抽取了
	 *
	 * @author zhaowei
	 * @param fieldName
	 * @param attrId
	 * @param p
	 * @return Long
	 * @create time 2014-4-14 下午2:10:02
	 */
	private static String fillByDb(String fieldName, String attrId, Product p) {

		if (p.getAttrMap() == null || p.getAttrMap().size() == 0) {
			return null;
		}
		List<Long> attrValIdList = p.getAttrValIdList(Long.parseLong(attrId));
		if (attrValIdList != null && attrValIdList.size() > 0) {
			long attrValId = attrValIdList.get(0);
			//todo:如果是无效属性值id,应该继续提取。
			p.setField(fieldName, attrValId + "db");
			return String.valueOf(attrValId);
		}
		return null;
	}

	// 1.标题+品牌导出品牌 2.标题+品牌中的型号导出品牌
	private String extractAssociatedField(Product p, List<String> enNameList, Map<String, String> enname2attrValIdMap,
			Map<String, Map<String, List<String>>> map, String associatedField, Long attrId, String curField) {

		String extBrandEnname = null;
		List<String> productContentList = getProductContentList(p);
		String brandId="";
		for (String productContent : productContentList) {
			List<String> extBrandByBrandList = new ArrayList<String>();
			List<String> extBrandByModelList = new ArrayList<String>();

			String partNameArray[] = productContent.split(" ");
			Set<String> partNameSet = new HashSet<String>();
			for (String partName : partNameArray) {
				partNameSet.add(partName.trim().toLowerCase());
			}

			for (String enName : enNameList) {
				// 1.标题+品牌导出品牌
				if (partNameSet.contains(enName)) {
					extBrandByBrandList.add(enName);
				}
				 brandId = enname2attrValIdMap.get(enName);

				// 2.标题+品牌中的型号导出品牌
				List<String> associatedFieldValList = map.get(brandId).get(associatedField);
				String associatedFieldVal = xtractKeyword(associatedFieldValList, productContent);
				if (StringUtil.isNotEmpty(associatedFieldVal)) {
					extBrandByModelList.add(enName);
				}

			}

			if (extBrandByBrandList.size() == 0 && extBrandByModelList.size() == 0) {
				return null;
			}

			// 1.求两个list的交集的第一个作为抽取的品牌
			List<String> interList = CommonUtil.getInterList(extBrandByBrandList, extBrandByModelList);
			if (interList.size() > 0) {
				extBrandEnname = interList.get(0);
			}

			// 2.否则求extBrandByBrandList第一个作为抽取的品牌
			if (extBrandEnname == null && extBrandByBrandList.size() > 0) {
				extBrandEnname = extBrandByBrandList.get(0);
			}
			if (StringUtils.isNotBlank(extBrandEnname)) {
				break;
			}
		}
		String strBrandValId = null;
		if (extBrandEnname != null) {
			//todo:如果提取到了，set添加属性值id, set清除无效属性值id
			strBrandValId = enname2attrValIdMap.get(extBrandEnname);
			if (strBrandValId == null) {
				return null;
			}
			List<Long> attrValIdList = new ArrayList<Long>();
			attrValIdList.add(Long.parseLong(strBrandValId));
			p.setAttrValIdList(attrId, attrValIdList);
			p.setField(curField, strBrandValId);
			//添加新的属性id
			p.addAttrValIdSet(Long.parseLong(strBrandValId));
			//清理此属性关联的无效的属性id
			removeAttrValId(p, attrId);
			//输出
			buildOutMap(p.getItemCode(),attrId,curField,strBrandValId,extBrandEnname);
		}
		return strBrandValId;
	}
	
	private void buildOutMap(long itemCode,Long attrId,String curField,String attrValId,String attrVal){
		//输出提取的字段：itemcode
		String itemCodeStr = String.valueOf(itemCode);
		StringBuffer keySb=new StringBuffer();
		if(attrId!=null){
			keySb.append(attrId).append("-").append(curField.substring(3)).append("-").append(attrValId).append("-").append(attrVal);
		}else{
			keySb.append(curField.substring(3)).append("-").append(attrVal);
		}
		if (outMap.get(curField) != null) {
			Map<String, String> enname2itemcodesMap = outMap.get(curField);
			if (enname2itemcodesMap.get(keySb.toString()) != null) {
				enname2itemcodesMap.put(keySb.toString(), enname2itemcodesMap.get(keySb.toString()) + "," + itemCodeStr);
			} else {
				enname2itemcodesMap.put(keySb.toString(), itemCodeStr);
			}

		} else {
			Map<String, String> enname2itemcodesMap = new HashMap<String, String>();
			enname2itemcodesMap.put(keySb.toString(), itemCodeStr);
			outMap.put(curField, enname2itemcodesMap);
		}
	}

	private void removeAttrValId(Product p, Long attrId) {
		if (p == null || attrId == null) {
			return;
		}
		List<SpuStandard> spuStandList = SpuStandardConsts.getSpuStandList(p.getProdLineId());
		if (spuStandList != null && spuStandList.size() > 0) {
			for (SpuStandard spuStand : spuStandList) {// 遍历规则，优先匹配最前面的规则
				if (spuStand.getAbandonMap() != null && spuStand.getAbandonMap().size() > 0) {
					for (Long key : spuStand.getAbandonMap().keySet()) {
						if (attrId == key) {
							for (Long valId : spuStand.getAbandonMap().get(key)) {
								if (p.getAttrValIdSet().contains(valId)) {
									//清理此属性关联的无效的属性id
									p.removeAttrValIdSet(valId);
									logger.debug("removeAttrValId attrId=" + attrId + " valId=" + valId);
								}
							}
						}

					}
				}
			}
		}
	}
	private boolean yAbandonAttrValId(Product p,String attrValIdStr) {
		logger.debug("attrValIdStr="+attrValIdStr);
		if (StringUtils.isBlank(attrValIdStr)) {
			return true;
		}
		Long attrValId=Long.parseLong(attrValIdStr);
		List<SpuStandard> spuStandList = SpuStandardConsts.getSpuStandList(p.getProdLineId());
		if (spuStandList != null && spuStandList.size() > 0) {
			for (SpuStandard spuStand : spuStandList) {// 遍历规则，优先匹配最前面的规则
				if (spuStand.getAbandonMap() != null && spuStand.getAbandonMap().size() > 0) {
					for (Long key : spuStand.getAbandonMap().keySet()) {
							for (Long valId : spuStand.getAbandonMap().get(key)) {
								logger.debug("valId="+valId + " attrValId="+attrValId );
								if (valId.equals(attrValId)) {
									return true;
								}
							}

					}
				}
			}
		}
		return false;
	}
	
	

	/**
	 * 
	 * @Description: 获取字段的属性值
	 * @author zhaowei
	 * @param attrValList
	 * @param p
	 * @param extField
	 * @param yExtField void
	 * @create time 2014-4-9 下午3:53:48
	 */
	private String extractField(List<String> attrValList, Product p, String fieldName, boolean yExtField) {
		String attrVal = "";
		if (attrValList == null || attrValList.size() <= 0) {
			return attrVal;
		}
		List<String> productContentList = getProductContentList(p);

		for (String str : productContentList) {
			attrVal = xtractKeyword(attrValList, str);
			if (StringUtil.isNotEmpty(attrVal)) {
				break;
			}
		}
		if (StringUtil.isEmpty(attrVal)) {
			return attrVal;
		}
		if (yExtField) {
			p.setExtField(fieldName, attrVal);
		
		//输出提取的字段：itemcode
		buildOutMap(p.getItemCode(),null,fieldName,null,attrVal);	
		}
		return attrVal;
	}

	/**
	 * 
	 * @Description: 包括产品名字、短描
	 *
	 * @author zhaowei
	 * @return List<String>
	 * @create time 2014-4-8 下午3:27:09
	 */
	private List<String> getProductContentList(Product p) {
		List<String> list = new ArrayList<String>();
		list.add(p.getProductName());
		list.add(p.getShortDescription());
		return list;
	}

}